<?php
	include('config.php');
	
	if(isset($_GET['email']) && isset($_GET['id']) && isset($_GET['token'])){
		$email = htmlentities(addslashes($_GET['email']));
		$uid = addslashes($_GET['id']);
		$hash = addslashes($_GET['token']);

		$query = 'SELECT U.user_id FROM USERS U WHERE user_id = '. $uid . ' AND password = \'' . $hash . '\'';		
		$results = mysql_query($query);
	
		if(mysql_num_rows($results) >= 1){
			$query = 'UPDATE USERS u SET u.email = \'' . $email . '\' WHERE u.user_id = ' . $uid;
			mysql_query($query);
			
			header('Location: index.php?page=profile&id=' . $uid);
		}else
			header('Location: index.php');
	}else if(isset($_GET['email']) && isset($_COOKIE['session_id']) && isset($_COOKIE['user_id'])){
		$hash = addslashes($_COOKIE['session_id']);
		$uid = addslashes($_COOKIE['user_id']);
		$email = htmlentities(addslashes($_GET['email']));
		
		$query = 'SELECT U.user_id FROM USERS U WHERE user_id = '. $uid . ' AND password = \'' . $hash . '\'';		
		$results = mysql_query($query);

		if(mysql_num_rows($results) >= 1){
			$subject = 'Oregon State Android Developers';
			$body = 'Please visit the following link in order to change your email:  http://web.engr.oregonstate.edu/~phillir2/project/changeEmail.php?id=' . $uid . '&email=' . $email . '&token=' . $hash;
			
			if(mail($email, $subject, $body)){
				header('Location: index.php?page=profile&id=' . $uid);
			}else{
				echo("<p>Email failed to send...</p>");
			} 
		}else
			header('Location: index.php');
	}else{
		header('Location: index.php');
	}
?>